package app.beit.fintrack.controller.search;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import app.beit.fintrack.bean.summary.SummaryTrackPidDataBean;
import app.beit.fintrack.controller.BaseController;
import app.beit.fintrack.controller.ResponseFintrack;
import app.beit.fintrack.controller.bean.SummaryPIDSessionBean;
import app.beit.fintrack.service.SummaryPIDService;
import app.beit.fintrack.utils.DateFormatUtils;
import app.beit.fintrack.utils.constr.MsgConstr;
import app.beit.fintrack.utils.constr.SessionConstr;
import app.beit.fintrack.utils.enums.ESearchByStatus;

@Controller
@RequestMapping("summarypid")
public class SummaryPIDController extends BaseController {
	private final Logger log = Logger.getLogger(this.getClass());

	@Autowired
	private SummaryPIDService summaryPIDService;

	@RequestMapping
	public String excute(final HttpServletRequest request, final @RequestParam(value="c", required=false) String c) {
		return "summarypid/summarypid";
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "searchByPID", method = RequestMethod.POST)
	@ResponseBody
	public ResponseFintrack<SummaryPIDSessionBean> searchByType(final HttpServletRequest request, final @RequestParam("hospitalCode") String hospitalCode,
			final @RequestParam("dateFromAdmidTime") String dateFromAdmidTime, final @RequestParam("dateToAdmidTime") String dateToAdmidTime, 
			final @RequestParam("searchBy") String searchBy, final @RequestParam("value") String value, 
			final @RequestParam("start") int start, final @RequestParam("end") int end) {
		this.log.info("SummaryPIDController Class");
		ResponseFintrack<SummaryPIDSessionBean> response = null;
		final SummaryPIDSessionBean psb = new SummaryPIDSessionBean();
		
		try {
			final Date fromDate = dateFromAdmidTime != null && dateFromAdmidTime.length()>0 ? DateFormatUtils.strToDate(dateFromAdmidTime) : null;
			final Date toDate = dateToAdmidTime != null && dateToAdmidTime.length()>0 ? DateFormatUtils.strToDate(dateToAdmidTime) : null;
			
			final List<SummaryTrackPidDataBean> results = this.summaryPIDService.getDetailsByPID(hospitalCode, searchBy, value, fromDate, toDate, start, end);
			final BigDecimal cntAll = this.summaryPIDService.getCountPerson(hospitalCode, searchBy, value, fromDate, toDate, null);
			final BigDecimal cntAppeal = this.summaryPIDService.getCountPerson(hospitalCode, searchBy, value, fromDate, toDate, ESearchByStatus.APPEAL);
			final BigDecimal cntNotPass = this.summaryPIDService.getCountPerson(hospitalCode, searchBy, value, fromDate, toDate, ESearchByStatus.NOT_PASS);
			final BigDecimal cntNotPassDeny = this.summaryPIDService.getCountPerson(hospitalCode, searchBy, value, fromDate, toDate, ESearchByStatus.NOT_PASS_C);
			final BigDecimal cntPass = cntAll.subtract(cntAppeal).subtract(cntNotPass).subtract(cntNotPassDeny);
			
			psb.setCountAll(cntAll);
			psb.setCountAppeal(cntAppeal);
			psb.setCountNotPass(cntNotPass);
			psb.setCountNotPassDeny(cntNotPassDeny);
			psb.setCountPass(cntPass);
			
			psb.setFromDate(fromDate);
			psb.setToDate(toDate);
			psb.setSearchBy(searchBy);
			psb.setSearchValue(value);
			psb.setHospitalCode(hospitalCode);
			
			psb.setPidDatas(this.buildData(results));
			response = super.responseSuccess();
			response.setDatas(psb);
			super.setAttributeInSession(request, SessionConstr.SESSION_SUMMARY_PID, psb);
		} catch (Exception e) {
			this.log.error(e.getMessage());
			e.printStackTrace();
			response = super.responseError(MsgConstr.ERROR_EXCEPTION_CODE, e.getMessage());
		}

		return response;
	}

	/**
	 * Export Excel
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="/{pid}", method=RequestMethod.GET)
	public ModelAndView exportXLS(final HttpServletRequest request, final HttpServletResponse response){
		final SummaryPIDSessionBean psb = (SummaryPIDSessionBean) super.getAttributeInSession(request, SessionConstr.SESSION_SUMMARY_PID);
		try{
			final Date fromDate = psb.getFromDate();
			final Date toDate = psb.getToDate();
			final int countAll = Integer.parseInt(psb.getCountAll().toString());
			final String searchBy = psb.getSearchBy();
			final String value = psb.getSearchValue();
			final String hospitalCode = psb.getHospitalCode();
			final List<SummaryTrackPidDataBean> results = this.summaryPIDService.getDetailsByPID(hospitalCode, searchBy, value, fromDate, toDate, 0, countAll);
			return new ModelAndView("excelViewByPID", "pidDataBeans", this.buildData(results));
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * build data before send to json
	 * @param results
	 * @return List<SummaryTrackPidDataBean>
	 */
	private List<SummaryTrackPidDataBean> buildData(final List<SummaryTrackPidDataBean> results){
		final List<SummaryTrackPidDataBean> beans = new ArrayList<SummaryTrackPidDataBean>();
		for(final SummaryTrackPidDataBean b : results){//loop for check main results
			String rep = b.getRepNo();
			String pid = b.getPid();
			String hCode = b.getHospitalCode();
			String admidDate = b.getAdmidDate() + b.getAdmidTime();
			String dischargeDate = b.getDischargeDate() + b.getDischargeTime();
			final String key = rep+pid+hCode+admidDate+dischargeDate;//main key
			final String mainBatchId = b.getBatchId();
			if(mainBatchId != null && mainBatchId.length() > 0){
				boolean isDup = false;
				int cnt = 0;
				for(final SummaryTrackPidDataBean bb : beans){
					rep = bb.getRepNo();
					pid = bb.getPid();
					hCode = bb.getHospitalCode();
					admidDate = bb.getAdmidDate() + bb.getAdmidTime();
					dischargeDate = bb.getDischargeDate() + bb.getDischargeTime();
					final String bbKey = rep+pid+hCode+admidDate+dischargeDate;
					final String bbBatchId = bb.getBatchId();
					if(bbKey.equalsIgnoreCase(key)){
						beans.get(cnt).setBatchId(bbBatchId + ", " + mainBatchId);
						isDup = true;
						break;
					}
				}
				if(!isDup){
					beans.add(b);
				}
			}else{
				beans.add(b);
			}
		}
		
		return beans;
	}

}
